<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\admin\service\UploadFileService;
use app\common\controller\AdminBaseController;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\MerchantInvoice;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;
use app\common\model\tang\Cost;
use app\common\model\tang\OrganizationConfig;
use app\common\model\tang\FloorConfig;
use app\common\model\tang\FormatsConfig;
use think\Exception;

class Merchant extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new MerchantModel();
    }

    public function index()
    {   
        if (IS_AJAX){
            return $this->model->getAdminPageData($this->param, 'id desc');
        }
        $activities = (new FormatsConfig())->select();
        //获取菜单列表
        $lc =(new FloorConfig())->select();
        //获取菜单列表
        $this->assign(compact("lc"));
        $this->assign(compact("activities"));
        return $this->fetch();
    }

    /**
     * 修改登录密码
     */
    public function updatePassword(){
        $param = $this->request->param();
        $id = $this->request->param("id/d");//父id

        $info = $this->model->find($id)->toArray();
        if(IS_AJAX){
            if($info['password']!=md5($param['oldpass'])){
                return self::JsonReturn("原密码输入错误", 0);
            }
            if(md5($param['newpassok'])!=md5($param['newpass'])){
                return self::JsonReturn("新密码和确认密码不一致", 0);
            }
            if(md5($param['newpass'])==md5($param['oldpass'])){
                return self::JsonReturn("不能和之前密码一样", 0);
            }
            $result = $this->model->where('id',$id)->update(['password'=>md5($param['newpass'])]);
            if($result){
                return self::JsonReturn("修改成功");
            }else{
                return self::JsonReturn("修改失败", 0);
            }

        }

        //获取菜单列表
        $this->assign('info',$info);

        return $this->fetch();
    }
    //导出
    public function export(){
        $this->model->getExportPageData($this->param,[]);
    }
    //导入发票信息
    /**
     * 导入
     */
    public function import()
    {
        header("content-type:text/html;charset=utf-8");
        //上传excel文件
        $res = UploadFileService::instance()->setUploadPath('merchant/invoice')->image('file');
        if ($res) {
            //获取上传到后台的文件名
            $fileName = $res['name'];
            //获取文件路径
            $filePath = app()->getRootPath() . 'public' . $res['thumb_path'];
            //获取文件后缀
            $suffix = $res['ext'];
            // 有Xls和Xlsx格式两种
            $reader = IOFactory::createReader('Xlsx');
        } else {
            return json(['status' => '1', 'message' => '文件过大或格式不正确导致上传失败-_-!']);
        }
//        $spreadsheet = $reader->load($filePath);

        //载入excel文件
//        $excel = $reader->load($filePath);
        $excel = IOFactory::load($filePath);
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        $merchantModel = new \app\common\model\tang\Merchant();
        $import_data = []; //数组形式获取表格数据
        $merchantInvoice = new MerchantInvoice();
        try {
            for ($i = 2; $i <= $row_num; $i++) {
                $data = [];
                $code = $excel->getActiveSheet()->getCell("B" . $i)->getValue();
                $invoiceType = $excel->getActiveSheet()->getCell("M" . $i)->getValue();
                $merchant_id = $merchantModel->where('code',$code)->value('id');
                if(empty($merchant_id)){
                    throw new Exception('第'.$i.'行'. $code.'未录入商户信息');
                }
                $this->model->update(['invoiceType'=>$invoiceType],['id'=>$merchant_id]);
                $title = $excel->getActiveSheet()->getCell("E" . $i)->getValue();
                $bankAccount = $excel->getActiveSheet()->getCell("F" . $i)->getValue();
                $bankName = $excel->getActiveSheet()->getCell("G" . $i)->getValue();
                $companyAddress = $excel->getActiveSheet()->getCell("H" . $i)->getValue();
                $taxNumber = $excel->getActiveSheet()->getCell("I" . $i)->getValue();
                $telephone = $excel->getActiveSheet()->getCell("J" . $i)->getValue();
                $type = $excel->getActiveSheet()->getCell("K" . $i)->getValue();
                $email = $excel->getActiveSheet()->getCell("L" . $i)->getValue();

                if(!empty($title)){
                    $data['merchant_id'] = $merchant_id;
                    $data['title'] = $title;
                    $data['bankAccount'] = $bankAccount;
                    $data['bankName'] = $bankName;
                    $data['companyAddress'] = $companyAddress;
                    $data['taxNumber'] = $taxNumber;
                    $data['telephone'] = $telephone;
                    $data['type'] = $type;
                    $data['email'] = $email;
                    $isfirst = $merchantInvoice->where(['merchant_id'=>$merchant_id])->find();
                    if(empty($isfirst)){
                        $merchantInvoice->save($data);
                    }else{
                        $merchantInvoice->where(['id'=>$isfirst['id']])->update($data);
                    }

                }
            }
        } catch (Exception $e) {
            return self::ajaxResult([], 0, 1, $e->getMessage());
        }

        return self::ajaxResult([], 0, 1, '导入成功');
    }
    /**
     * 编辑发票信息
     */
    public function updateInvoice(){
        $id = $this->request->param('id');
        $merchant  = $this->model->find($id)->toArray();
        $param = $this->request->param();
        $info = (new MerchantInvoice())->where('merchant_id',$id)->find();
        if(IS_AJAX){
            $param['merchant_id'] = $param['id'];
            unset($param['__token__']);
            unset($param['id']);
            if(empty($info)){
                $result = (new MerchantInvoice())->save($param);
            }else{
                $result = (new MerchantInvoice())->update($param,['id'=>$info['id']]);

            }
            if($result){
                return self::JsonReturn("更新成功");
            }else{
                return self::JsonReturn("更新失败111", 0);
            }

        }
        unset($info['id']);
        $this->assign(compact("info","merchant"));
        $this->assign('id',$id);
        $this->assign('merchantid',$merchant);
        return $this->fetch();
    }
    public function upBalance(){
        $id = $this->request->param("id/d");//父id
//        dump($id);
        $start_balance = $this->model->where('id',$id)->value('start_balance');
        $frozen_balance = $this->model->where('id',$id)->value('frozen_balance');
        $change = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>1,'edit'=>1,'status'=>1])->sum('amount');
        $zhuan = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>4,'edit'=>1])->sum('amount');
        $chu = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>4,'edit'=>2])->sum('amount');
        $balance_pay = (new BalanceLog())->where(['merchant_id'=>$id,'status'=>1,'type'=>3])->sum('amount');
        $cost = (new Cost())->where(['merchant_id'=>$id,'pay_status'=>1])->whereNotNull('pointId')->whereIn('cost_type_id',[45,46])->sum('all_amount');
//        dump('期初余额:'.$start_balance/100);
//        dump('冻结金额:'.$frozen_balance/100);
//        dump('充值金额:'.$change/100);
//        dump('转入余额:'.$zhuan/100);
//        dump('转出余额:'.$chu/100);
//        dump('账单缴费:'.$cost/100);
//        dd();
        $result =$this->model->update([
//            'balance'=>bcsub(bcsub(bcadd(bcadd(bcadd($start_balance,$change),$zhuan),$frozen_balance),-$chu),$cost)
            'balance'=>bcsub(bcsub(bcsub(bcsub(bcadd(bcadd($start_balance,$change),$zhuan),-$chu),$cost),$frozen_balance),$balance_pay)
        ],[
            'id'=>$id
        ]);
        if ($result) {
            return self::JsonReturn("更新成功");
        } else {
            return self::JsonReturn("更新失败",0);
        }
    }
    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:添加编辑
     */
    public function add()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            if(!empty($data['start_time'])){
                $data['start_time'] = strtotime($data['start_time']);
            }
            if(!empty($data['end_time'])){
                $data['end_time'] = strtotime($data['end_time']);
            }
            if($data['balance']>0){
                $data['balance'] = $data['balance']*100;
            }
            if(!empty($data['start_balance'])){
                $data['start_balance'] = $data['start_balance']*100;
            }
            if(empty($data['merchant_sn'])){
                return self::JsonReturn("商户号不能为空", 0);
            }
            return $this->model->doAll($data);
        }
        $id = $this->request->param("id/d");//父id
//        $info = $this->model->with(['MerchantMobile'])->find($id)->toArray();
        if(!empty($id)){
            $info = $this->model->find($id);
            if ($info){
                $info['start_time'] = date('Y-m-d',$info['start_time']);
                $info['end_time'] = date('Y-m-d',$info['end_time']);
                $info['balance'] =  $info['balance']/100;
                $info['start_balance'] = $info['start_balance']/100;
            }
            //商户没有指定任务的话,则不选中
            if($info['task_id']){
                $task = $this->getTask();
                //循环匹配
                $taskInfo = explode(',',$info['task_id']);
                foreach ($taskInfo as $k=>$v){
                    foreach ($task as $kk=>$vv){
                        if($v==$vv['value']){
                            $task[$kk]['selected']=true;
                        }
                    }
                }
            }else{
                $task = $this->getTask();
            }
            //获取菜单列表
            $this->assign(compact("info", "id"));
        }else{
            $info['type']=1;
            $task = $this->getTask();
            $this->assign(compact("info", "id"));
        }
        $orange = OrganizationConfig::where('pid',0)->select();
        if(!empty($info['organization'])){
            $orange_one = OrganizationConfig::where('pid',$info['organization'])->select();
            $this->assign(compact("orange_one", "id"));
        }
        $lc =(new FloorConfig())->select();
        $activities = (new FormatsConfig())->select();
        //获取菜单列表
        $this->assign(compact("lc"));
        //获取菜单列表
        $this->assign(compact("info", "id"));
        $this->assign(compact("orange", "id","activities"));
        $this->assign('task',$task);

        return $this->fetch();
    }
    /**
     * 任务选项
     */
    public function getTask(){
        $task = \app\common\model\tang\Task::field('id,name')->select();
        foreach ($task as $k=>$v){
            $task[$k]['value'] =$v['id'];
            $task[$k]['selected'] = false;
        }
        return $task;
    }
    /**
     * 选择组织下拉框
     */
    public function change(){
        $pid = $this->request->param('pid');
        $orange = OrganizationConfig::where('pid',$pid)->field('id,name')->select()->toArray();
        return self::ajaxResult($orange);
    }
    /**
     * @return string|\think\response\Json
     * @throws \Exception  手动添加余额
     */
    public function addBalance(){

        if(IS_AJAX){
            $param = $this->param;
            Db::startTrans();
            try {
                $this->model->where('id',$param['id'])->inc('balance',$param['balance']*100)->update();
                $log['edit'] = $param['balance']>0 ?1:2;
                $log['merchant_id'] = $param['id'];
                $log['is_top_up'] = 1;
                $log['amount'] = $param['balance']*100;
                $log['mobile'] = $param['mobile'];
                $log['remark'] = '后台手动充值';
                (new BalanceLog())->save($log);
                Db::commit();
                return self::JsonReturn("充值成功");
            }catch (\Exception $exception){
                Db::rollback();
                return false;
            }

        }

        $id = $this->request->param('id/d');
        if(!empty($id)){
            $info = $this->model->find($id)->toArray();
            //获取菜单列表
            $this->assign('info',$info);
        }
        return $this->fetch();
    }

    /**
     * @return string|\think\response\Json
     * @throws \Exception  查看详情
     */
    /**
     * 查看订单详情
     */
    public function detail()
    {
        $param = $this->param;
        $result = (new Cost())->getAdminPageData($this->param, 'id desc',['merchant_id'=>$param['id']]);
        $json = json_decode($result->getContent(),true);
        $costData=$json['data'];
        if(count($costData)>0){
            foreach ($costData as $k=>$v){
                if($v['type']!=4||$v['type']!=5){
                    unset($costData[$k]);
                }
            }
        }
        $this->assign('cost',$costData);
        return $this->fetch();
    }
    public function balance()
    {
        $id = $this->request->param("id/d");//父id
        if (IS_AJAX){
            $mode = new BalanceLog();
            $param = $this->request->param();
            $param['merchant_id'] = $param['id'];
            return $mode->getAdminPageData($param,'id desc');
        }
        $this->assign(compact("id"));
        return $this->fetch();
    }

    public function undel() {
        // TODO: Implement delById() method.
        $id = $this->request->param("ids/d");//父id
        $info = $this->model->find($id);
        $isUse = $this->model->where(['merchant_sn'=>$info['merchant_sn'],'status'=>1])->find();
        if($isUse){
            return self::JsonReturn("该商户水电表已有商户使用",0);
        }
        $result = $this->model->update([
            'status'=> 1
        ],['id'=>$id]);
        if ($result) {
            return self::JsonReturn("解冻成功");
        } else {
            return self::JsonReturn("解冻失败",0);
        }
    }

}
